/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.strategy.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.customize.mysql.utils.MysqlUtil;
import com.pig4cloud.pigx.common.customize.redis.constants.CommonRedisConstants;
import com.pig4cloud.pigx.common.customize.redis.utils.RedisUtils;
import com.pig4cloud.pigx.common.customize.utils.CommonUtil;
import com.pig4cloud.pigx.strategy.dto.StrategySwitchContractConditionDTO;
import com.pig4cloud.pigx.strategy.entity.StrategyContract;
import com.pig4cloud.pigx.strategy.entity.StrategySwitchContract;
import com.pig4cloud.pigx.strategy.enums.StrategySwitchContractEnum;
import com.pig4cloud.pigx.strategy.enums.StrategyTaskContractEnum;
import com.pig4cloud.pigx.strategy.executor.contract.order.StrategyOrderContractHandlerManager;
import com.pig4cloud.pigx.strategy.mapper.StrategyStopOrderContractMapper;
import com.pig4cloud.pigx.strategy.mapper.StrategySwitchContractMapper;
import com.pig4cloud.pigx.strategy.service.StrategySwitchContractService;
import com.pig4cloud.pigx.strategy.util.StrategyContractUtil;
import com.pig4cloud.pigx.strategy.vo.StrategySwitchContractVO;
import com.pig4cloud.pigx.system.constant.SystemPlatformConstant;
import com.pig4cloud.pigx.system.entity.SystemProduct;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 策略开关-合约
 *
 * @since 2022-11-24 10:39:27
 */
@Service
@RequiredArgsConstructor
public class StrategySwitchContractServiceImpl extends ServiceImpl<StrategySwitchContractMapper, StrategySwitchContract> implements StrategySwitchContractService {

    private final RedisUtils redisUtils;
    private final StrategyContractUtil strategyContractUtil;
    private final StrategyStopOrderContractMapper strategyStopOrderContractMapper;
    private final StrategyOrderContractHandlerManager strategyOrderContractHandlerManager;

    /**
     * 分页查询
     *
     * @param page      分页条件
     * @param condition 查询条件
     * @return {@link Page <  StrategySwitchContractVO >}
     * @since 2023/2/13 09:49
     */
    @Override
    public Page<StrategySwitchContractVO> page(Page<StrategySwitchContract> page, StrategySwitchContractConditionDTO condition) {
        StrategyContract strategy = strategyContractUtil.getStrategyCache(condition.getStrategyId(), true);
        if (!Objects.isNull(strategy)) {
            // 查询张数面值
            SystemProduct product = strategyContractUtil.getProductById(strategy.getProductId(), false);
            condition.setSheetValue(product.getSheetValue());

            // 查询价格
            BigDecimal price = null;
            if (product.getPlatformId().equals(SystemPlatformConstant.OKX)) {
                price = redisUtils.getSymbolPrice(strategy.getSymbolName(), CommonRedisConstants.OKX + CommonRedisConstants.LAST_PRICE);
            }
            condition.setCurrentPrice(price);
        }


        int pageCount = baseMapper.pageCount(condition);
        if (pageCount == 0) {
            return MysqlUtil.EMPTY_PAGE;
        }

        int startIndex = CommonUtil.getStartIndex((int) page.getCurrent(), (int) page.getSize());
        int endIndex = CommonUtil.getEndIndex((int) page.getCurrent(), (int) page.getSize());
        List<StrategySwitchContractVO> list = baseMapper.page(condition, startIndex, endIndex);

        Page<StrategySwitchContractVO> resPage = new Page<>(page.getCurrent(), page.getSize(), pageCount);
        resPage.setRecords(list);

        // 收集任务id
        List<Long> taskIdList = resPage.getRecords().stream()
                .map(StrategySwitchContractVO::getTaskId)
                .collect(Collectors.toList());
        // 查询任务下的当前止盈止损数量
        List<Map<String, Long>> countStopOrder = strategyStopOrderContractMapper.countCurrentByTaskIdList(taskIdList);
        list.forEach(i -> {
            // 翻译字典项
            i.setStatus(StrategySwitchContractEnum.Status.findName(i.getStatus()));
            i.setTaskStatus(Strings.isBlank(i.getTaskStatus()) ?
                    "无任务"
                    : StrategyTaskContractEnum.Status.findName(i.getTaskStatus()));

            // 设置当前止盈止损数量
            for (Map<String, Long> c : countStopOrder) {
                if (Objects.equals(i.getTaskId(), c.get("taskId"))) {
                    i.setCurrentStopOrderCount(c.getOrDefault("count", 0L));
                    break;
                }
            }
            if (Objects.isNull(i.getCurrentStopOrderCount())) {
                i.setCurrentStopOrderCount(0L);
            }

            // 查询用户ok余额
            try {
                BigDecimal accountBalance = strategyOrderContractHandlerManager.accountBalance(i.getUserId(), strategy.getPlatformId());
                i.setOkBalance(accountBalance.setScale(8, RoundingMode.HALF_UP));
            } catch (Throwable e) {
            }
        });

        return resPage;
    }
}
